<?php

namespace app\index\controller;

use Alpay\AopClient;
use Alpay\request\AlipaySystemOauthTokenRequest;
use Alpay\request\AlipayTradeCreateRequest;
use think\Controller;
use think\Db;
use think\Request;
use Wxpay\JsApiPay;

class Wxpay extends Controller
{

    public function index(Request $request)
    {
        $orderarr = [
            //自己的订单id
            'orderid' => 'zlwxpay' . time(),
            'shopdesc' => '这是支付测试',
            'price' => 0.01
        ];
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($ua, 'MicroMessenger') == true) {
            //微信支付
            return $this->wxpay1($orderarr);
        } else {
            if (strpos($ua, 'AlipayClient') == true) {
                // dump('支付宝支付');
                return $this->alpay($orderarr);
            } else {
                echo '请用手机支付宝或者微信扫码';
            }
        }
    }

    public function wxpay1($orderarr)
    {
        $jsapi = new JsApiPay();
        //获取openID
        $openid = $jsapi->GetOpenid();
        //调用统一下单接口创建一个订单
        $input = new \WxPayUnifiedOrder();
        //商品描述(必须)
        $input->SetBody($orderarr['shopdesc']);
        //附加数据(非必须)
        // $input->SetAttach("网页jsapi支付");
        //商户订单号(必须)
        $shoporder = $orderarr['orderid'];
        $input->SetOut_trade_no($shoporder);
        //支付金额(单位:分)(必须)
        $wxprice = intval(round($orderarr['price'] * 100));
        $input->SetTotal_fee($wxprice);
        //交易开始时间20091227091010(非必须)
        $input->SetTime_start(date("YmdHis"));
        //交易结束的时间就是订单关闭不能支付的时间(非必须)
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //订单优惠劵标识符(非必须)
        $input->SetGoods_tag("yhj");
        //支付回调地址(必须)
        $input->SetNotify_url("http://leqq00.eicp.net/tp5/public/index.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        //获取微信公众号和商户平台的配置项
        $config = new \Wxpay\WxPayConfig();
        //调用下单接口进行下单(返回订单)
        $wxorder = \WxPayApi::unifiedOrder($config, $input);
        //获取jsapi支付的参数
        $jsapiparam = $jsapi->GetJsApiParameters($wxorder);
        //判断订单是否已经支付
        if (isset($jsapiparam['msg'])) {
            die($jsapiparam['msg']);
        }
        //商户自己的订单号
        $this->assign('oid', $shoporder);
        //微信jsapi返回的支付订单号
        $this->assign('pid', $wxorder['prepay_id']);
        $this->assign('jsapi', $jsapiparam);
        return $this->fetch('wx');
    }

    public function alpay($orderarr)
    {
        //支付宝类
        $aliPayaop = new AopClient();
        //获取code码
        $code = $this->getToken($aliPayaop->appId);
        //获取access_token和user_id
        $alre = new AlipaySystemOauthTokenRequest();
        $alre->setGrantType('authorization_code');
        $alre->setCode($code);
        $responce = $aliPayaop->execute($alre);
        if ($baseInfo = $responce->alipay_system_oauth_token_response) {
            $userid = $baseInfo->user_id;     //支付用户的支付宝id
        } else {
            echo '<h1>' . $responce->error_response->code . ':' . $responce->error_response->sub_msg . '</h1>';
            exit();
        }
        //调用下单接口
        $order = new AlipayTradeCreateRequest();
        $orderinfo = [
            'out_trade_no' => $orderarr['orderid'], //你自己的商品订单号，不能重复
            'total_amount' => $orderarr['price'],     //付款金额，单位:元
            'subject' => $orderarr['shopdesc'],   //订单标题
            'buyer_id' => $userid,      //付钱的人支付宝号
        ];
        $order->setBizContent(json_encode($orderinfo, JSON_UNESCAPED_UNICODE));
        $resule = $aliPayaop->execute($order);
        if (!empty($resule->alipay_trade_create_response) && $resule->alipay_trade_create_response->code == 10000) {
            $this->assign('tradeno', $resule->alipay_trade_create_response->trade_no);
        } else {
            exit('获取订单号失败');
        }
        return $this->fetch('alpay');
    }


    public function uporder(Request $request)
    {
        $oid = $request->param('oid');
        $pid = $request->param('pid');
        $res = Db::table('orderpay')->where('order', $oid)->update(['state' => 2, 'wxorder' => $pid]);
        return $res;
    }

    /**
     * @param $appid
     * 获取code码
     */
    public function getToken($appid)
    {
        if (!isset($_GET['auth_code'])) {
            //触发支付宝返回code码
            $scheme = 'http://';
            $uri = $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING'];
            if ($_SERVER['REQUEST_URI']) {
                $uri = $_SERVER['REQUEST_URI'];
            }
            $urlObj["app_id"] = $appid;
            $urlObj["redirect_uri"] = urlencode($scheme . $_SERVER['HTTP_HOST'] . $uri);
            $urlObj["scope"] = 'auth_base';
            $urlObj["state"] = 'alpay';
            $buff = "";
            foreach ($urlObj as $k => $v) {
                if ($k != "sign") {
                    $buff .= $k . "=" . $v . "&";
                }
            }
            $buff = trim($buff, "&");
            $url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?" . $buff;
            Header("Location: $url");
            exit();
        } else {
            //返回code码
            return ($_GET['auth_code']);
        }
    }
}
